

using System;

namespace NodeBasedSkillEditor.Model.Node.RT
{
    public class Node_SelectExecute_RT : RT_Node
    {
        public RT_FlowPort FlowIn_RT;

        public RT_SingleValuePort Index_RT;

        public RT_SingleValuePort RepeatIndex_RT;

        public RT_FlowPort[] Executes_RT;

        public Node_SelectExecute_RT(Node_SelectExecute sourceData, RT_DAG parentDag) : base(sourceData, parentDag)
        {
            FlowIn_RT = new RT_FlowPort(EPortIOType.Input, sourceData.FlowIn, this);

            Index_RT = new RT_SingleValuePort(EPortIOType.Input, sourceData.Index, this);

            RepeatIndex_RT = new RT_SingleValuePort(EPortIOType.Input, sourceData.RepeatIndex, this);

            Executes_RT = BuildRTPortArrayFromGroup<RT_FlowPort>(EPortIOType.Output, sourceData.Executes);
        }


        public override (EDagExeState, RT_Node) ForewardExecute(DAG_Executor executor)
        {
            if (Executes_RT.Length > 0)
            {
                int index = Index_RT.GetValue(executor).ToInteger().Item2;
                bool isRepeatIndex = RepeatIndex_RT.GetValue(executor).ToBoolean().Item2;
                int exeListLen = Executes_RT.Length;
                int validIndex = index;
                if (index < 0 || index >= exeListLen)
                {
                    validIndex = isRepeatIndex ? index % exeListLen : XDFLib.XMath.Clamp(index, 0, exeListLen - 1);
                }

                var portToExe = Executes_RT[validIndex];
                return TryForewardByPort(portToExe);
            }
            else
            {
                return (EDagExeState.Backward, null);
            }
        }

    }
}